﻿using Coolzon.Common.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Coolzon.Realtime.ServerApp
{
    /// <summary>
    /// 读取配置信息
    /// </summary>
    public static class ConfigLoader
    {
        public static bool Load()
        {
            Config.AppSettings = new AppSettings();
            Config.AppSettings.StorageDirectory = string.Format("{0}\\coolzon\\2.0\\Realtime.ServerApp\\", GetSystemDrive());
            Config.AppSettings.WebAppBaseUrl = System.Configuration.ConfigurationManager.AppSettings["Coolzon.WebApp.BaseUrl"];
            if(string.IsNullOrEmpty(Config.AppSettings.WebAppBaseUrl))
            {
                return false;
            }

            string configJsonString = HttpUtil.GetString(Config.GetConfigUrl());
            try
            {
                Config.Current = JsonConfigUtil.LoadFromString<Config>(configJsonString);
            }
            catch(Exception ex)
            {
                return false;
            }
            return true;
        }

        private static string GetSystemDrive()
        {
            System.IO.DirectoryInfo dirWindows = new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));

            System.IO.DirectoryInfo dirRoot = null;
            System.IO.DirectoryInfo dirParent = dirWindows.Parent;
            while (dirParent != null)
            {
                dirRoot = dirParent;
                dirParent = dirParent.Parent;
            }
            return dirRoot.FullName;
        }

        class HttpUtil
        {
            public static string GetString(string url)
            {
                try
                {
                    HttpClient client = new HttpClient();
                    return client.GetStringAsync(url).Result;
                }
                catch (Exception ex)
                {

                }
                return null;
            }
        }
    }
}
